// 付费墙逻辑处理
(function() {
  'use strict';

  // 检查用户订阅状态
  function checkSubscriptionStatus() {
    const subscriptionStatus = localStorage.getItem('subscription_status');
    const subscriptionExpiry = localStorage.getItem('subscription_expiry');
    
    if (subscriptionStatus === 'active' && subscriptionExpiry) {
      const expiryDate = new Date(subscriptionExpiry);
      const now = new Date();
      
      if (expiryDate > now) {
        return true; // 订阅有效
      } else {
        // 订阅已过期，清除本地存储
        localStorage.removeItem('subscription_status');
        localStorage.removeItem('subscription_expiry');
        return false;
      }
    }
    return false;
  }

  // 检查免费文章数量
  function checkFreeArticles() {
    const freeArticlesRead = parseInt(localStorage.getItem('free_articles_read') || '0');
    const maxFreeArticles = parseInt(window.MAGAZINE_CONFIG?.freeArticles || '3');
    
    return {
      canRead: freeArticlesRead < maxFreeArticles,
      currentCount: freeArticlesRead,
      maxCount: maxFreeArticles
    };
  }

  // 增加免费文章阅读计数
  function incrementFreeArticleCount() {
    const current = parseInt(localStorage.getItem('free_articles_read') || '0');
    localStorage.setItem('free_articles_read', (current + 1).toString());
  }

  // 显示付费墙
  function showPaywall() {
    const paywallElement = document.getElementById('paywall');
    if (paywallElement) {
      paywallElement.style.display = 'block';
      
      // 添加动画效果
      setTimeout(() => {
        paywallElement.classList.add('show');
      }, 100);
    }
  }

  // 隐藏付费墙
  function hidePaywall() {
    const paywallElement = document.getElementById('paywall');
    if (paywallElement) {
      paywallElement.style.display = 'none';
    }
  }

  // 初始化 Stripe
  function initializeStripe() {
    const stripePublishableKey = window.MAGAZINE_CONFIG?.stripePublishableKey;
    if (!stripePublishableKey) {
      console.error('Stripe publishable key not configured');
      return null;
    }
    
    return Stripe(stripePublishableKey);
  }

  // 处理订阅按钮点击
  function handleSubscribeClick() {
    const stripe = initializeStripe();
    if (!stripe) return;

    const subscribeBtn = document.getElementById('subscribe-btn');
    if (subscribeBtn) {
      subscribeBtn.addEventListener('click', async function() {
        try {
          // 显示加载状态
          subscribeBtn.innerHTML = '<span class="loading"></span> 处理中...';
          subscribeBtn.disabled = true;

          // 创建 Checkout Session
          const response = await fetch('/api/create-checkout-session', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              priceId: 'price_1YOUR_PRICE_ID', // 替换为你的 Stripe Price ID
              successUrl: window.location.href,
              cancelUrl: window.location.href,
            }),
          });

          if (!response.ok) {
            throw new Error('Failed to create checkout session');
          }

          const { sessionId } = await response.json();

          // 重定向到 Stripe Checkout
          const { error } = await stripe.redirectToCheckout({
            sessionId: sessionId,
          });

          if (error) {
            throw error;
          }

        } catch (error) {
          console.error('Subscription error:', error);
          alert('订阅失败，请稍后重试。');
          
          // 恢复按钮状态
          subscribeBtn.innerHTML = '立即订阅 ¥365/年';
          subscribeBtn.disabled = false;
        }
      });
    }
  }

  // 处理邀请码验证
  function handleInviteCode() {
    const inviteCodeInput = document.getElementById('invite-code');
    const submitInviteBtn = document.getElementById('submit-invite');
    
    if (inviteCodeInput && submitInviteBtn) {
      submitInviteBtn.addEventListener('click', function() {
        const inviteCode = inviteCodeInput.value.trim();
        
        if (!inviteCode) {
          alert('请输入邀请码');
          return;
        }

        // 验证邀请码格式
        const inviteCodePattern = /^ELITE-[A-Z0-9]{4}-[A-Z0-9]{4}$/;
        if (!inviteCodePattern.test(inviteCode)) {
          alert('邀请码格式不正确，格式应为：ELITE-XXXX-XXXX');
          return;
        }

        // 这里应该调用后端 API 验证邀请码
        // 为了演示，我们假设邀请码有效
        localStorage.setItem('invite_code_valid', 'true');
        localStorage.setItem('invite_code', inviteCode);
        
        // 隐藏邀请码输入，显示注册表单
        document.getElementById('invite-section').style.display = 'none';
        document.getElementById('register-section').style.display = 'block';
      });
    }
  }

  // 处理注册
  function handleRegistration() {
    const registerForm = document.getElementById('register-form');
    
    if (registerForm) {
      registerForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(registerForm);
        const email = formData.get('email');
        const password = formData.get('password');
        const inviteCode = localStorage.getItem('invite_code');

        // 这里应该调用后端 API 注册用户
        // 为了演示，我们假设注册成功
        localStorage.setItem('user_email', email);
        localStorage.setItem('registration_complete', 'true');
        
        alert('注册成功！欢迎加入精英杂志！');
        
        // 关闭模态框或重定向
        const modal = bootstrap.Modal.getInstance(document.getElementById('registerModal'));
        if (modal) {
          modal.hide();
        }
      });
    }
  }

  // 初始化文章阅读逻辑
  function initializeArticleReading() {
    const isArticlePage = document.querySelector('article[data-article-id]');
    
    if (isArticlePage) {
      const articleId = isArticlePage.getAttribute('data-article-id');
      const hasSubscription = checkSubscriptionStatus();
      const freeArticleStatus = checkFreeArticles();
      
      // 检查是否已经阅读过这篇文章
      const readArticles = JSON.parse(localStorage.getItem('read_articles') || '[]');
      const hasReadThisArticle = readArticles.includes(articleId);
      
      if (hasSubscription) {
        // 订阅用户，显示完整内容
        hidePaywall();
      } else if (hasReadThisArticle) {
        // 已经阅读过这篇文章，显示完整内容
        hidePaywall();
      } else if (freeArticleStatus.canRead) {
        // 免费文章额度内，显示完整内容并增加计数
        hidePaywall();
        incrementFreeArticleCount();
        
        // 记录已阅读的文章
        readArticles.push(articleId);
        localStorage.setItem('read_articles', JSON.stringify(readArticles));
      } else {
        // 需要付费
        showPaywall();
      }
      
      // 更新免费文章计数显示
      updateFreeArticleCounter(freeArticleStatus);
    }
  }

  // 更新免费文章计数显示
  function updateFreeArticleCounter(status) {
    const counterElement = document.getElementById('free-article-counter');
    if (counterElement) {
      counterElement.textContent = `免费文章：${status.currentCount}/${status.maxCount}`;
      
      if (status.currentCount >= status.maxCount) {
        counterElement.classList.add('text-danger');
      } else {
        counterElement.classList.add('text-success');
      }
    }
  }

  // 处理登录
  function handleLogin() {
    const loginForm = document.getElementById('login-form');
    
    if (loginForm) {
      loginForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(loginForm);
        const email = formData.get('email');
        const password = formData.get('password');

        // 这里应该调用后端 API 验证登录
        // 为了演示，我们假设登录成功
        localStorage.setItem('user_email', email);
        localStorage.setItem('subscription_status', 'active');
        localStorage.setItem('subscription_expiry', new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString());
        
        alert('登录成功！');
        
        // 刷新页面以显示订阅内容
        window.location.reload();
      });
    }
  }

  // 处理登出
  function handleLogout() {
    const logoutBtn = document.getElementById('logout-btn');
    
    if (logoutBtn) {
      logoutBtn.addEventListener('click', function() {
        // 清除所有本地存储的用户信息
        localStorage.removeItem('user_email');
        localStorage.removeItem('subscription_status');
        localStorage.removeItem('subscription_expiry');
        localStorage.removeItem('invite_code_valid');
        localStorage.removeItem('invite_code');
        localStorage.removeItem('registration_complete');
        
        alert('已登出');
        window.location.reload();
      });
    }
  }

  // 初始化所有功能
  function initialize() {
    // 等待 DOM 加载完成
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', initialize);
      return;
    }

    // 初始化各个功能模块
    handleSubscribeClick();
    handleInviteCode();
    handleRegistration();
    handleLogin();
    handleLogout();
    initializeArticleReading();
    
    console.log('Paywall system initialized');
  }

  // 启动初始化
  initialize();
})();